package com.learn.grpc.loadbalance;

import com.learn.grpc.grpc.LbServiceGrpc;
import com.learn.grpc.hello.PingRequest;
import com.learn.grpc.hello.PingResponse;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;

@Slf4j
public class LbGrpcImpl extends LbServiceGrpc.LbServiceImplBase {

    private Integer port;

    public LbGrpcImpl(Integer port) {
        this.port = port;
        log.info("启动服务，端口号:{}", port);
    }

    @Override
    public void ping(PingRequest request, StreamObserver<PingResponse> responseObserver) {

        String content = request.getContent();
        System.out.println("请求参数:" + content);

        PingResponse response = PingResponse.newBuilder()
                .setCode(0).setMessage("success")
                .setData(String.format("[%s] serverPort:%s, content:%s", LocalDateTime.now(), port, content))
                .build();

        // 向客户端写入数据
        responseObserver.onNext(response);
        // 通知客户端，写入完成
        responseObserver.onCompleted();
    }

}
